#ifndef DATABASE_HPP
#define DATABASE_HPP

#include <QtSql>
#include <QMessageBox>
#include <pthread.h>
#include <assert.h>

class database{
private:
    static pthread_mutex_t mtx;
    static database * instance;
    database(){
        auto ret=createConnection();
        assert(ret);
    }
    ~database(){
        deleteConnection();
    }

    QSqlDatabase db;
public:
    QSqlDatabase& getDB(){
        return this->db;
    }

    static database* getInstance(){
        if(instance==nullptr){
            pthread_mutex_lock(&mtx);
            if(instance==nullptr){
                instance = new database();
            }
            pthread_mutex_unlock(&mtx);
        }
        return instance;
    }

    bool createConnection()
    {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("/home/wjy1230/db/TC.db");
        if (!db.open()) {
            QMessageBox::critical(nullptr, "Error", db.lastError().text());
            return false;
        }
        return true;
    }

    void deleteConnection(){
        db.close();
    }
};

#endif // DATABASE_HPP
